var container;
var zoom;
var rootData;
var depthInfo;
var rootName; //根节点名称

jQuery(document).ready(function() {
	/* resizeScreen();*/

	//selectChange();
	var child = document.getElementById("product_tree");
	child.innerHTML = '';
	getData();
	//初始化缩放比例
});

/**
 * 获取数据
 */
/**

 * 将list装换成tree
 * @param {Object} myId 数据主键id
 * @param {Object} pId  数据关联的父级id
 * @param {Object} children 子节点的节点名称
 * @param {Object} paramList list数据集合
 */
function listToTree(myId, pId, children, paramList) {
	function recursion(id, pId, all, item) {
		let childrenList = all.filter(ele => ele[pId] === item[id]);
		if (childrenList && childrenList.length > 0) {
			childrenList.forEach(function(f) {
				recursion(id, pId, all, f);
			})
			let myChildrenList = item[children];
			if (myChildrenList === undefined) {
				myChildrenList = [];
			}
			childrenList.forEach(o => myChildrenList.push(o));
			item[children] = myChildrenList;
		}
	}

	if (!paramList || paramList.length === 0) {
		return [];
	}
	let list = JSON.parse(JSON.stringify(paramList));
	let parentList = list.filter(ele => ele[pId] === null || ele[pId] === undefined);
	if (!parentList) {
		return [];
	}
	parentList.forEach(function(it) {
		recursion(myId, pId, list, it);
	})
	return parentList;
}

/**
 * 拆分数组
 * @param {Object} array
 */
var splitArray = function(array) {

	if (array == null || array.length == 0) {
		return array;
	}

	let length = array.length;
	let firstArrayLength = Math.ceil(length / 2);
	let array1 = [],
		array2 = [];
	for (var i = 0; i < firstArrayLength; i++) {
		array1[i] = array[i]
	}

	let j = 0;
	for (var i = firstArrayLength; i < array.length; i++, j++) {
		array2[j] = array[i]
	}
	return [array1, array2];
}

var getData = function() {
	let tree = listToTree('name', 'parent_name', 'children', data);
	let trees = splitArray(tree[0].children);
	// 测试内容
	rootData = {
		"downward": {
			"direction": "downward",
			"name": "origin",
			"children": trees[0]
		},
		"upward": {
			"direction": "upward",
			"name": "origin",
			"children": trees[1]
		}
	}
	rootName = tree[0].name;
	drawing();
};
var drawing = function() {
	var _this = this;
	// var rootName = ''; //根节点的名字
	var rootRectWidth = 0; //根节点rect的宽度
	var downwardLength = 0,
		upwardLength = 0;
	var forUpward = true

	var treeChart = function(d3Object) {
		this.d3 = d3Object;
		this.directions = ['upward', 'downward'];
	};


	treeChart.prototype.drawChart = function() {
		// First get tree data for both directions.
		this.treeData = {};
		var self = this;
		self.directions.forEach(function(direction) {
			self.treeData[direction] = _this.rootData[direction];
		});
		// rootName = '上海冰鉴信息科技有限公司';
		rootRectWidth = _this.rootName.length * 15;
		//获得upward第一级节点的个数
		//todo 隐藏上面部分的功能
		//upwardLength = _this.rootData.upward.children.length;
		//获得downward第一级节点的个数
		downwardLength = _this.rootData.downward.children.length;
		self.graphTree(self.getTreeConfig());
	};

	treeChart.prototype.getTreeConfig = function() {
		var treeConfig = {
			'margin': {
				'top': 10,
				'right': 5,
				'bottom': 0,
				'left': 30
			}
		}

		treeConfig.chartWidth = (screen.availWidth - treeConfig.margin.right - treeConfig.margin.left);
		treeConfig.chartHeight = (900 - treeConfig.margin.top - treeConfig.margin.bottom);
		treeConfig.centralHeight = treeConfig.chartHeight / 3; //开始位置
		treeConfig.centralWidth = treeConfig.chartWidth / 2;
		treeConfig.linkLength = 100;
		treeConfig.duration = 500; //动画时间
		return treeConfig;
	};

	treeChart.prototype.graphTree = function(config) {
		var self = this;
		var d3 = this.d3;
		var linkLength = config.linkLength;
		var duration = config.duration;
		var hasChildNodeArr = [];
		var id = 0;

		//横向线
		var diagonal2 = d3.svg.diagonal()
			.projection(function(d) {
				return [d.y, d.x];
			});

		//折线
		var diagonal = function(obj) {
			var s = obj.source
			var t = obj.target

			let multiplier = s.x > t.x ? -1 : s.x < t.x ? 1 : 0
			let path = s.y > t.y ? s.y / 3 + (t.y * 2) / 3 : s.y / 3 + (t.y * 2) / 3 + 15
			return (
				'M' +
				s.x +
				',' +
				(s.y) +
				'L' +
				s.x +
				',' +
				path +
				'L' +
				(t.x - 10) +
				',' +
				path +
				// pathA+
				'L' +
				(t.x - 10) +
				',' +
				t.y
			)
		}
		window.diagonal = diagonal;

		var zoom = d3.behavior.zoom()
			.scaleExtent([0.5, 2])
			.on('zoom', redraw);
		var svg = d3.select('#product_tree')
			.append('svg')
			.attr('width', config.chartWidth + config.margin.right + config.margin.left)
			.attr('height', config.chartHeight + config.margin.top + config.margin.bottom)
			.attr('xmlns', 'http://www.w3.org/2000/svg')
			.on('mousedown', disableRightClick)
			.call(zoom)
			.on('dblclick.zoom', null);
		var treeG = svg.append('g')
			.attr('transform', 'translate(' + config.margin.left + ',' + config.margin.top + ')');

		//箭头(下半部分)
		var markerDown = svg.append("marker")
			.attr("id", "resolvedDown")
			.attr("markerUnits", "strokeWidth") //设置为strokeWidth箭头会随着线的粗细发生变化
			.attr("markerUnits", "userSpaceOnUse")
			.attr("viewBox", "0 -5 10 10") //坐标系的区域
			.attr("refX", 0) //箭头坐标
			.attr("refY", 0)
			.attr("markerWidth", 12) //标识的大小
			.attr("markerHeight", 12)
			.attr("orient", "auto") //绘制方向，可设定为：auto（自动确认方向）和 角度值
			.attr("stroke-width", 2) //箭头宽度
			.append("path")
			.attr("d", "M0,-5L10,0L0,5") //箭头的路径
			.attr('fill', '#4d85ff'); //箭头颜色  
		//箭头(上半部分)
		var markerUp = svg.append("marker")
			.attr("id", "resolvedUp")
			.attr("markerUnits", "strokeWidth") //设置为strokeWidth箭头会随着线的粗细发生变化
			.attr("markerUnits", "userSpaceOnUse")
			.attr("viewBox", "0 -5 10 10") //坐标系的区域
			.attr("refX", 0) //箭头坐标
			.attr("refY", 0)
			.attr("markerWidth", 12) //标识的大小
			.attr("markerHeight", 12)
			.attr("orient", "-90") //绘制方向，可设定为：auto（自动确认方向）和 角度值
			.attr("stroke-width", 2) //箭头宽度
			.append("path")
			.attr("d", "M0,-5L10,0L0,5") //箭头的路径
			.attr('fill', '#4d85ff'); //箭头颜色  

		// Initialize the tree nodes and update chart.
		for (var d in this.directions) {
			var direction = this.directions[d];
			var data = self.treeData[direction];
			data.x0 = config.centralWidth;
			data.y0 = config.centralHeight;
			data.children.forEach(collapse);
			update(data, data, treeG);
		}

		function update(source, originalData, g) {
			//console.log(source)
			var direction = originalData['direction'];
			forUpward = direction == 'upward';
			var node_class = direction + 'Node';
			var link_class = direction + 'Link';
			var downwardSign = (forUpward) ? -1 : 1;
			var nodeColor = (forUpward) ? '#37592b' : '#8b4513';

			var isExpand = false;
			var statusUp = true;
			var statusDown = true;
			var nodeSpace = 115; //节点之间左右间隔
			var tree = d3.layout.tree().sort(sortByDate).nodeSize([nodeSpace, 0]);
			var nodes = tree.nodes(originalData);
			var links = tree.links(nodes);
			var offsetX = -config.centralWidth;
			nodes.forEach(function(d) {
				d.y = downwardSign * (d.depth * linkLength) + config.centralHeight;
				d.x = d.x - offsetX;
				if (d.name == 'origin') {
					d.x = config.centralWidth;
					d.y += downwardSign * 0; // 上下两树图根节点之间的距离
				}
			});

			// 节点容器g
			var node = g.selectAll('g.' + node_class)
				.data(nodes, function(d) {
					return (d.id || (d.id = ++id));
				});
			var nodeEnter = node.enter()
				.append('g')
				.attr('class', node_class)
				.attr('transform', function(d) {
					return 'translate(' + (source.x0) + ',' + source.y0 + ')';
				})
				.style('cursor', function(d) {
					return (d.name == 'origin') ? '' : (d.children || d._children) ? 'pointer' : '';
				});
			// .on('click', click);
				

			nodeEnter.append("svg:rect")
				.attr("x", function(d) {
					return (d.name == 'origin') ? -(rootRectWidth / 2) : -60;
				})
				.attr("y", function(d) {
					return (d.name == 'origin') ? -20 : forUpward ? -52 : 12;
				})
				.attr("width", function(d) {
					return (d.name == 'origin') ? rootRectWidth : 100;
				})
				.attr("height", function(d) {
					return (d.name == 'origin') ? 40 : 70;
				})
				.attr("rx", 2) //圆角大小
				.style("stroke", function(d) {
					return (d.name == 'origin') ? "#1078AF" : "#2488FF";
				})
				.style("fill", function(d) {
					return (d.name == 'origin') ? "#0080E3" : "#FFF"; //节点背景色
				});

			nodeEnter.append('circle')
				.attr('r', 1e-6);
			//第一段公司名称
			nodeEnter.append("text")
				.attr("class", "linkname")
				.attr("x", function(d) {
					return (d.name == 'origin') ? '0' : "-58";
				})
				.attr('dy', function(d) {
					return (d.name == 'origin') ? '.35em' : forUpward ? '-30' : '24';
				})
				.attr("text-anchor", function(d) {
					return (d.name == 'origin') ? 'middle' : "start";
				})
				.attr('fill', '#000')
				.text(function(d) {
					if (d.name == 'origin') {
						// return ((forUpward) ? '根节点TOP' : '根节点Bottom');
						return _this.rootName;
					}
					if (d.repeated) {
						return '[Recurring] ' + d.name;
					}
					return (d.name.length > 7) ? d.name.substr(0, 7) : d.name;
				})
				.style({
					'fill-opacity': 1e-6,
					'fill': function(d) {
						if (d.name == 'origin') {
							return '#fff';
						}
					},
					'font-size': function(d) {
						return (d.name == 'origin') ? 14 : 14;
					},
					'cursor': "pointer"
				})
				.on('click', Change_modal);
			//第二段公司名称
			nodeEnter.append("text")
				.attr("class", "linkname")
				.attr("x", "-58")
				.attr("dy", function(d) {
					return (d.name == 'origin') ? '.35em' : forUpward ? '-13' : '35';
				})
				.attr("text-anchor", function() {
					return (d.name == 'origin') ? 'middle' : "start";
				})
				.text(function(d) {
					return d.name.substring(7, 14);
				})
				.style({
					'fill': "#333333",
					'font-size': function(d) {
						return (d.name == 'origin') ? 14 : 14;
					},
					'cursor': "pointer"
				});

			//第三段公司名称
			nodeEnter.append("text")
				.attr("class", "linkname")
				.attr("x", "-58")
				.attr("dy", function(d) {
					return (d.name == 'origin') ? '.35em' : forUpward ? '4' : '46';
				})
				.attr("text-anchor", function() {
					return (d.name == 'origin') ? 'middle' : "start";
				})
				.text(function(d) {
					return d.name.substr(14, d.name.length);
				})
				.style({
					'fill': "#333333",
					'font-size': function(d) {
						return (d.name == 'origin') ? 14 : 14;
					},
					'cursor': "pointer"
				});

			// Transition nodes to their new position.原有节点更新到新位置
			var nodeUpdate = node.transition()
				.duration(duration)
				.attr('transform', function(d) {
					return 'translate(' + d.x + ',' + d.y + ')';
				});

			//缩放开关
			nodeUpdate.select('circle')
				.attr('r', function(d) {
					return (d.name == 'origin') ? 0 : (hasChildNodeArr.indexOf(d) == -1) ? 0 : 6;
				})
				.attr('cy', function(d) {
					return (d.name == 'origin') ? -20 : (forUpward) ? -59 : 90;
				})
				.attr('cx', function(d) {
					return (d.name == 'origin') ? -10 : (forUpward) ? -10 : -8;
				})
				.style('fill', function(d) {
					return hasChildNodeArr.indexOf(d) != -1 ? "#4d85ff" : "";
					// if (d._children || d.children) { return "#fff"; } else { return "rgba(0,0,0,0)"; }
				})
				.style('stroke', function(d) {
					return hasChildNodeArr.indexOf(d) != -1 ? "#4d85ff" : "";
					// if (d._children || d.children) { return "#8b4513"; } else { return "rgba(0,0,0,0)"; }
				})
				.style('fill-opacity', function(d) {
					if (d.children) {
						return 1; //收缩开关的背景色透明度
					}
				})
				// Setting summary node style as class as mass style setting is
				// not compatible to circles.
				.style('stroke-width', function(d) {
					if (d.repeated) {
						return 5;
					}
				});
			//代表是否展开的+-号
			nodeEnter.append("svg:text")
				.attr("class", "isExpand")
				.attr("x", function(d) {
					return forUpward ? -10 : -8;
				})
				.attr("dy", function(d) {
					return forUpward ? -56 : 94; //设置关闭符号大小
				})

				.attr("text-anchor", "middle")
				.style("fill", "#fff")
				.text(function(d) {
					if (d.name == 'origin') {
						return '';
					}
					return hasChildNodeArr.indexOf(d) != -1 ? "+" : "";
					/* if (d._children || d.children) {
					  return "+";
					} */
				})
				.on('click', click)

			nodeUpdate.select('text').style('fill-opacity', 1)

			var nodeExit = node.exit().transition()
				.duration(duration)
				.attr('transform', function(d) {
					return 'translate(' + source.x + ',' + source.y + ')';
				})
				.remove();
			nodeExit.select('circle')
				.attr('r', 1e-6)
			nodeExit.select('text')
				.style('fill-opacity', 1e-6);

			var link = g.selectAll('path.' + link_class)
				.data(links, function(d) {
					return d.target.id;
				});

			//
			link.enter().insert('path', 'g')
				.attr('class', link_class)
				.attr('stroke', function(d) {
					return 'red'
				})
				.attr('fill', "none")
				.attr('stroke-width', '1px')
				.attr('opacity', 0.5)
				.attr('d', function(d) {
					var o = {
						x: source.x0,
						y: source.y0
					};
					let r = diagonal({
						source: o,
						target: o
					});
					console.log(r)
					return r;
				})
				.attr("marker-end", function(d) {
					return forUpward ? "url(#resolvedUp)" : "url(#resolvedDown)";
				}) //根据箭头标记的id号标记箭头;
				.attr("id", function(d, i) {
					return "mypath" + i;
				})
			link.transition()
				.duration(duration)
				.attr('d', diagonal);
			link.exit().transition()
				.duration(duration)
				.attr('d', function(d) {
					var o = {
						x: source.x,
						y: source.y
					};
					return diagonal({
						source: o,
						target: o
					});
				})
				.remove();
			nodes.forEach(function(d) {
				d.x0 = d.x;
				d.y0 = d.y;
			});

			function Change_modal() {
				_this.Modal = true
			}

			function click(d) {
				if (forUpward) {

				} else {
					if (d._children) {
						console.log('对外投资--ok')
					} else {
						console.log('对外投资--no')
					}
				}
				isExpand = !isExpand;
				if (d.name == 'origin') {
					return;
				}
				if (d.children) {
					d._children = d.children;
					d.children = null;
					d3.select(this).text('+')
				} else {
					d.children = d._children;
					d._children = null;
					// expand all if it's the first node
					if (d.name == 'origin') {
						d.children.forEach(expand);
					}
					d3.select(this).text('-')
				}
				update(d, originalData, g);
			}
		}

		function expand(d) {
			if (d._children) {
				d.children = d._children;
				d.children.forEach(expand);
				d._children = null;
			}
		}


		function collapse(d) {
			if (d.children && d.children.length != 0) {
				d._children = d.children;
				d._children.forEach(collapse);
				d.children = null;
				hasChildNodeArr.push(d);
			}
		}


		function redraw() {
			// console.log("缩放比例", d3.event.scale)
			// console.log("缩放比例2", d3.event.translate)
			treeG.attr('transform', 'translate(' + d3.event.translate + ')' +
				' scale(' + d3.event.scale + ')');
		}

		function disableRightClick() {
			// stop zoom
			if (d3.event.button == 2) {
				console.log('No right click allowed');
				d3.event.stopImmediatePropagation();
			}
		}


		function sortByDate(a, b) {
			var aNum = a.name.substr(a.name.lastIndexOf('(') + 1, 4);
			var bNum = b.name.substr(b.name.lastIndexOf('(') + 1, 4);
			return d3.ascending(aNum, bNum) ||
				d3.ascending(a.name, b.name) ||
				d3.ascending(a.id, b.id);
		}
	};

	var d3GenerationChart = new treeChart(d3);
	d3GenerationChart.drawChart();

};


var downloadfun = function() { //下载

	// 注释该方法为svg 直接下载
	//  var SvgSaver = require('svgsaver');                 // if using CommonJS environment
	//  var svgsaver = new SvgSaver();                      // creates a new instance
	//  var svg = document.querySelector('#product_tree');         // find the SVG element
	//  svgsaver.asSvg(svg);                                // save as SVG

	var g = document.getElementById('product_tree').getElementsByTagName('g')[0].getBBox();
	var gbox = document.getElementById('product_tree').getElementsByClassName('gbox')[0];
	var x = -g.x; //计算偏移位置
	var y = -g.y;
	gbox.style.transform = "translate(" + x + 'px' + "," + y + "px" + ")  scale(1)"; //偏移位置
	var svgbox = $('#product_tree svg')
	var boxwidth = svgbox.width;
	var boxheight = svgbox.height;
	svgbox.attr('width', g.width)
	svgbox.attr('height', g.height)
	var canvas = document.createElement("canvas");
	var c = canvas.getContext('2d');
	//新建Image对象
	//svg内容
	var svg = document.getElementById('product_tree').innerHTML;
	var img = new Image();

	img.src = 'data:image/svg+xml,' + unescape(encodeURIComponent(svg)); //svg内容中可以有中文字符
	img.src = 'data:image/svg+xml,' + svg; //svg内容中不能有中文字符
	img.src = 'data:image/svg+xml;base64,' + window.btoa(unescape(encodeURIComponent(svg)));
	//图片初始化完成后调用
	img.onload = function() {
		//将canvas的宽高设置为图像的宽高
		canvas.width = img.width;
		canvas.height = img.height + 60;
		c.fillStyle = "#fff";
		c.fillRect(0, 0, canvas.width, canvas.height);
		c.drawImage(img, 0, 30);
		//canvas画图片

		var a = document.createElement("a");
		a.download = "png";
		a.href = canvas.toDataURL("image/png");
		a.click();
	}
	//图片转换为base64后 传给后端 发邮件 
	gbox.style.transform = ''
	// svgbox.attr('width',boxwidth)
	// svgbox.attr('height',boxheight)
	svgbox.attr('width', "100%")
	svgbox.attr('height', 600)

	// 结束
}
